﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PersonalFinances.Models;
using PersonalFinances.Models.BusinessLogic;

namespace PersonalFinances.Controllers
{
    [Authorize(Roles = "Administrator")]
    public class HomeController : Controller
    {
        FinancesDBContext db = new FinancesDBContext();

        public ActionResult Index()
        {
            ViewBag.Message = "Welcome to ASP.NET MVC!";
            var notes = db.Notes.OrderBy(x => x.Date).ToList();
            
            return View(notes);
        }

        public ActionResult About()
        {
            return View();
        }

        public ActionResult ShowMonth(DateTime month)
        {
            var nextMonth = month.AddMonths(1);
            var notes = db.Notes.Where(item => item.Date >= month && item.Date < nextMonth).Select(item=>item);
            return View(notes.ToList());
        }

        public String ShowDay(DateTime day)
        {
            var nextDay = day.AddDays(1);
            var notes = db.Notes.Include("Category").Where(item => item.Date >= day && item.Date < nextDay).Select(item => item).ToList();
            var categories = notes.Select(item=> item.Category).Distinct();
            foreach (var cat in categories.ToList())
            {
                cat.Notes = notes.Where(note => note.Category == cat).Select(n => n).ToList();
            }

            categories.ToList().ForEach(cat => cat.Notes = notes.Where(note => note.Category == cat).Select(note => note).ToList());
            string t = "<ul>";
            foreach (var item in categories.ToList())
            {
                t+="<li>" +  item.Name +"|";
                double total = 0;
                foreach (var note in item.Notes)
                {
                    total += note.Value;
                }
                if (!item.InOrOut)
                {
                    total *= -1;
                }
                t+=total +"</li>";
            }
            t+="</ul>";
            return t;
        }
    }
}
